package main

import (
	"net/http"
	"net/http/pprof"
	"os"
	"os/signal"
	"syscall"

	"gitee.com/lihaiping1603/utils/log"
	"gitee.com/lihaiping1603/utils/xhttp"
	"github.com/gin-gonic/gin"
)

func onCreateNotifyConfig(w http.ResponseWriter, r *http.Request) {
	log.Info("request method:%s", r.Method)
	w.WriteHeader(http.StatusOK)
	w.Write([]byte("hello"))
	log.Info("write hello ok...")
}

func main() {
	engine := gin.New()
	engine.Use(gin.Logger(), gin.Recovery())
	server := xhttp.NewServerEngine(engine)

	engine.GET("/panic", func(c *gin.Context) {
		keep_raw_query := false
		defer func() {
			if err := recover(); err != nil {
				log.Error("panic happened:err:%v", err)
			}
			c.String(http.StatusOK, "panic")
			log.Info("keep_raw_query=%t, write panic ok...", keep_raw_query)
		}()
		keep_raw_query = true
		panic(c)
		log.Info("receive uri /panic")
	})
	debugRouter := engine.Group("/debug")
	debugRouter.GET("/statatics", func(c *gin.Context) {
		log.Info("request method:get")
		c.String(http.StatusOK, "statatics")
		log.Info("write statatics ok...")
	})

	engine.PUT("/*any", func(c *gin.Context) {
		path := c.Param("any")
		log.Info("request method:%s,path:%s", c.Request.Method, path)
		c.String(http.StatusOK, "put hello")
		log.Info("put:write hello ok...")
	})

	pprofRouter := engine.Group("/debug/pprof")
	{
		pprofRouter.GET("/", gin.WrapF(pprof.Index))
		pprofRouter.GET("/cmdline", gin.WrapF(pprof.Cmdline))
		pprofRouter.GET("/profile", gin.WrapF(pprof.Profile))
		pprofRouter.POST("/symbol", gin.WrapF(pprof.Symbol))
		pprofRouter.GET("/symbol", gin.WrapF(pprof.Symbol))
		pprofRouter.GET("/trace", gin.WrapF(pprof.Trace))
		pprofRouter.GET("/allocs", gin.WrapH(pprof.Handler("allocs")))
		pprofRouter.GET("/block", gin.WrapH(pprof.Handler("block")))
		pprofRouter.GET("/goroutine", gin.WrapH(pprof.Handler("goroutine")))
		pprofRouter.GET("/heap", gin.WrapH(pprof.Handler("heap")))
		pprofRouter.GET("/mutex", gin.WrapH(pprof.Handler("mutex")))
		pprofRouter.GET("/threadcreate", gin.WrapH(pprof.Handler("threadcreate")))
	}
	//engine.Handle(http.MethodGet|http.MethodPut,"/*", func(c *gin.Context) {
	//	log.Info("request method:put")
	//	c.String(http.StatusOK, "hello")
	//	log.Info("write hello ok...")
	//})

	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
	go func() {
		//wait
		<-c
		server.Stop()
		log.Info("stop server...")
	}()

	if err := server.Start(":9090", "", ""); err != nil {
		log.Error("%s", err.Error())
	}
	return
}
